package com.demo.oauth.handlers;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.demo.commons.results.CommonEnum;
import com.demo.commons.results.CommonResult;
import com.demo.commons.results.Results;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		Throwable cause = authException.getCause();
		if(null == cause) {
			cause = authException.fillInStackTrace();
			if(null == cause) {
				return;
			}
		}
		CommonResult<?> result = null;
		if (cause instanceof InvalidTokenException) {
			result = Results.build(CommonEnum.ACCESS_TOKEN_ERROR);
		} else {
			result = Results.build(CommonEnum.AUTH_VER);
		}
		response.setContentType("application/json");
		response.setStatus(HttpServletResponse.SC_OK);
		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(response.getOutputStream(), result);
		log.error("access_token校验异常", authException);
	}

}
